var box = null;

$(function(){
	box = $("#contentBox");
	init();
});

function init()
{
	var select = $('#company_id');
	select.html('');
	
	var ajaxoptions = {
		type    : 'GET',
		url     : 'ajax.php?page=cmp&cmd=list',
		dataType: 'JSON',
		success : function(result, status) {
			eval ('var json = ' + result);
			for (var key in json)
			{
				var option = $('<option />').val(key).append(json[key]);
				select.append(option);    
			}
		},
		error   : function(xhr, status, error) {
			alert(xhr);
		}
	}
	
	$.ajax(ajaxoptions);

    box.html(
		'<button id="btnAddNewRow">Добавить</button>'+
		'<button id="btnDeleteRow">Удалить</button>'+
		'<table cellpadding="0" cellspacing="0" border="0" class="display" id="tab"></table>' );
	var tabBox = $('#tab', box);
    var tab = tabBox.dataTable( {
		"sPaginationType": "full_numbers",
		"bLengthChange": false,
		"bJQueryUI": false,
		"bInfo": true,
		"bFilter": true,
		"bAutoWidth": false,
		"iDisplayLength": 25,
		"bServerSide": false,
		"sAjaxSource": "ajax.php?page=usr&cmd=sel",
		/*
        */
        "aoColumns": [
			// u.id, u.email, c.title company, u.info
            { "sTitle": "id", "bVisible": false },
            { "sTitle": "EMail", "sWidth": "20%" },
            { "sTitle": "Партнер", "sWidth": "20%" },
            { "sTitle": "Доп.инф.", "sWidth": "60%", type: "textarea" }
        ],
		"oLanguage": {
			"oPaginate": {
				"sNext": "След.",
				"sFirst": "Первая",
				"sLast": "Послед.",
				"sPrevious": "Пред."
			},
			"sSearch": "Поиск:",
            "sZeroRecords": "Ничего не выбрано",
            "sInfo": "_START_-_END_ из _TOTAL_",
            "sInfoEmpty": "Показано от 0 до 0 из 0 строк",
            "sInfoFiltered": "(Доступно _MAX_)"
        }
    } ).makeEditable({
		sUpdateURL: "ajax.php?page=usr&cmd=upd",
        sAddURL: "ajax.php?page=usr&cmd=ins",
        sDeleteURL: "ajax.php?page=usr&cmd=del",
		sAddNewRowFormId: "formAddNewRow",
		"aoColumns" : [
			{},
			null,
			{
				type: 'textarea',
				submit:'Сохранить',
				fnOnCellUpdated: function(sStatus, sValue, row, column, settings)
				{
				}
			}
		],
		fnOnAdding: function()
		{ 	
			console.log("Adding new record");
			return true;
		},
		fnOnAdded: function(status)
		{ 	
			console.log("Add action finished. Status - " + status);
		},
		fnOnDeleting: function (tr, id, fnDeleteRow)
		{
			// console.log(print_r(tr[0].childNodes[0]));
			if(confirm('Вы действительно хотите удалить пользователя ['+ tr[0].childNodes[0].innerText +'] ?'))
			{
				fnDeleteRow(id);
			}
		}
	});
	
	console.log(print_r(tab[0].dataset));

}


